import React, { useState } from 'react';
import { NavBar, Button, Toast } from 'antd-mobile';
import { useNavigate, useLocation } from 'react-router-dom';
import axios from '../../axios';
import './Com/Payment.css';

interface PaymentOrder {
  orderId: string;
  productName: string;
  price: number;
  quantity: number;
  orderTime: string;
}

const Payment: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const order = location.state?.order as PaymentOrder;
  const [loading, setLoading] = useState(false);

  const handleBack = (): void => {
    navigate(-1);
  };

  // 处理支付
  const handlePayment = async () => {
    if (!order) {
      Toast.show('订单信息不存在');
      return;
    }

    try {
      setLoading(true);
      Toast.show({
        content: '正在创建支付订单...',
        position: 'center',
        duration: 1000
      });

      // 从 localStorage 获取用户ID
      const yonghuId = localStorage.getItem('yonghuId');
      if (!yonghuId) {
        Toast.show('请先登录');
        return;
      }

      // 调用后端创建支付订单
      const response = await axios.post('http://localhost:3000/hy/yonghu/create-payment', {
        orderId: order.orderId, //订单号
        amount: order.price, //商品价格
        productName: order.productName, //商品名称
        userId: yonghuId //用户ID
      });

      if (response.data.code === 200) {
        const { payUrl, outTradeNo } = response.data.data;
        
        console.log('支付参数:', payUrl); // 调试用
        console.log('商户订单号:', outTradeNo); // 调试用
        
        Toast.show({
          content: '正在跳转到支付宝...',
          position: 'center',
          duration: 1000
        });

        // 跳转到支付宝APP支付
        setTimeout(() => {
          if (typeof payUrl === 'string') {
            // 在移动端打开支付宝APP进行支付
            window.location.href = payUrl;
          } else {
            console.error('支付参数格式错误:', payUrl);
            Toast.show('支付链接格式错误');
          }
        }, 1000);
      } else {
        Toast.show(response.data.message || '创建支付订单失败');
      }
    } catch (error) {
      console.error('支付失败:', error);
      Toast.show('支付失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  if (!order) {
    return (
      <div className="payment-page">
        <NavBar onBack={handleBack}>支付</NavBar>
        <div className="payment-error">
          <p>订单信息不存在</p>
        </div>
      </div>
    );
  }

  return (
    <div className="payment-page">
      <NavBar onBack={handleBack}>支付</NavBar>
      
      <div className="payment-content">
        {/* 支付金额 */}
        <div className="payment-amount">
          <h3 style={{textAlign: 'center'}}>支付金额</h3>
          <div className="amount-display">
            <span className="currency">¥</span>
            <span className="amount">{order.price.toFixed(2)}</span>
          </div>
        </div>

        {/* 支付按钮 */}
        <div className="payment-actions">
          <Button
            block
            color="primary"
            size="large"
            loading={loading}
            onClick={handlePayment}
            className="pay-button"
          >
            立即支付
          </Button>
        </div>
      </div>
    </div>
  );
};

export default Payment; 